require "base_def"

local web_login_api = require "web_login_api"

--web服务器返回数据
local function get_request_api(path)
    if web_login_api.get_request_api[path] then
        return web_login_api.get_request_api[path]
    else
        log.info("get_request_api path is ",path)
    end
end

local function response(fd, code, param)
    --log.info("code= ", code)
    --log.info("param= ", param)
    if not param then
        local ok, err = httpd.write_response(sockethelper.writefunc(fd), code, "request error")
        if not ok then
            skynet.error(string.format("fd = %d, %s", fd, err))
        end
        return
    end

    local req_data = "method not defined"
    log.info("service_web_connect param.path=", param.path)
    local f = get_request_api(param.path)
    if f then
        --log.info("service_web_connect param.body=", param.body)
        req_data = f(param.body)
    end
    --解决跨域的问题
    local ok, err = httpd.write_response(sockethelper.writefunc(fd), code, req_data, {['Access-Control-Allow-Origin'] = '*' })     
    if not ok then
        -- if err == sockethelper.socket_error , that means socket closed.
        skynet.error(string.format("fd = %d, %s", fd, err))
    end
end

local function request(fd, ip_addr)
    log.info("service_web_connect request: ", "fd= "..fd.." ip_addr= "..ip_addr)
    socket.start(fd)
    -- limit request body size to 8192 (you can pass nil to unlimit)
	local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(fd), nil)
    skynet.error('service_web_connect request code, url, method, ip_addr', code, url, method, ip_addr)
    if code then
        if code ~= 200 then
            response(fd, code)
        else
            local tmp = {}
            if header.host then
                tmp.host = header.host
            end
            local path, query = urllib.parse(url)
            tmp.path = path
            assert(query)
            tmp.query = urllib.parse_query(query)
            tmp.header = header
            tmp.body = body
            --log.info("tmp=", tmp.query)
            response(fd, code, tmp)
        end
    else
        if url==sockethelper.socket_error then
            skynet.error("socket closed")
        else
            skynet.error(url)
        end
    end
    socket.close(fd)
end

--web监听
skynet.start(function()  
    local web_port = tonumber(skynet.getenv('web_port'))
    local id = socket.listen("0.0.0.0", web_port)
    log.info("service_web_connect Listen web port: ", web_port)
    socket.start(id, function(new_id, addr)
        local s = string.find(addr, ":")
        local client_addr = string.sub(addr, 1, s-1)
        request(new_id, client_addr)
    end)
end)
